package com.imis.module.websocket.bus;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imis.base.constant.CacheConstant;
import com.imis.base.constant.DictCodeConstant;
import com.imis.base.constant.enums.ArgumentResponseEnum;
import com.imis.base.globle.response.BaseResponse;
import com.imis.base.globle.response.CommonResponse;
import com.imis.base.util.CurrentUserUtils;
import com.imis.module.base.BaseBus;
import com.imis.module.system.model.vo.DictVO;
import com.imis.module.system.model.vo.SysWebsocketMessageInfoVO;
import com.imis.module.system.service.ISysDictService;
import com.imis.module.system.service.ISysWebsocketMessageService;
import com.imis.module.websocket.WebSocket;
import com.imis.module.websocket.dto.PagingQueryMessageDTO;
import com.imis.module.websocket.dto.WebSocketMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * InstantMessagingBus<br>
 * 即时通讯 业务处理类
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2020年07月24日 17:44
 */
@Slf4j
@Service
public class InstantMessagingBus extends BaseBus {

    /**
     * 前后端交互的类实现消息的接收推送
     */
    private WebSocket webSocket;

    @Autowired
    public void setWebSocket(WebSocket webSocket) {
        this.webSocket = webSocket;
    }

    /**
     * WebSocket信息传递记录 服务类
     */
    private ISysWebsocketMessageService sysWebsocketMessageService;

    @Autowired
    public void setSysWebsocketMessageService(ISysWebsocketMessageService sysWebsocketMessageService) {
        this.sysWebsocketMessageService = sysWebsocketMessageService;
    }

    /**
     * 字典项 服务类
     */
    private ISysDictService sysDictService;

    @Autowired
    public void setSysDictService(ISysDictService sysDictService) {
        this.sysDictService = sysDictService;
    }

    /**
     * 查询在线人数接口
     *
     * @return Result -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/7/24 17:57
     */
    public CommonResponse<Integer> queryOnlineNumber() {
        Integer onlineNumber = this.redisUtil.hget(CacheConstant.SESSION_ID_CLIENT_ID, CacheConstant.SESSION_ONLINE_COUNT, Integer.class);
        return new CommonResponse(onlineNumber == null ? 0 : onlineNumber);
    }

    /**
     * 查看历史消息接口
     *
     * @param pagingQueryMessageDTO - 分页WebSocket信息对象
     * @return Result -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/7/25 13:30
     */
    public CommonResponse<Page<SysWebsocketMessageInfoVO>> pagingQueryHistoricalMassages(final PagingQueryMessageDTO pagingQueryMessageDTO) {
        // 1、WebSocket信息
        pagingQueryMessageDTO.setSenderIdentification(CurrentUserUtils.getUserNameByToken());
        Page<SysWebsocketMessageInfoVO> sysWebsocketMessageListByParameter = this.sysWebsocketMessageService.pagingQueryHistoricalMassages(pagingQueryMessageDTO);
        if (!sysWebsocketMessageListByParameter.getRecords().isEmpty()) {
            // 2、WebSocket信息状态（0：发送成功，1：等待接收，2：发送异常）
            List<DictVO> dictList = this.sysDictService.queryDictItemsByDictCode(DictCodeConstant.MESSAGE_STATE);
            Map<String, String> messageState = new HashMap<>();
            dictList.forEach(
                    dict -> messageState.put(dict.getValue(), dict.getText())
            );
            sysWebsocketMessageListByParameter.getRecords().forEach(
                    sysWebsocketMessageInfoVO -> {
                        String stateKey = String.valueOf(sysWebsocketMessageInfoVO.getMessageState());
                        if (messageState.containsKey(stateKey)) {
                            sysWebsocketMessageInfoVO.setMessageStateText(messageState.get(stateKey));
                        }
                    }
            );
        }
        return new CommonResponse(sysWebsocketMessageListByParameter);
    }

    /**
     * 发送WebsocketMessages信息
     *
     * @param webSocketMessage - WebSocket信息对象
     * @return Result -
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/7/24 18:29
     */
    public BaseResponse sendMassage(final WebSocketMessageDTO webSocketMessage) {
        // 设置发送人
        webSocketMessage.setSenderIdentification(CurrentUserUtils.getUserNameByToken());
        boolean sendMassages = this.webSocket.sendMassages(webSocketMessage);
        ArgumentResponseEnum.WEBSOCKET_PAGE_QUERY_ERR.assertIsTrue(sendMassages);
        return new CommonResponse();
    }

}
